package org.jaaksi.kottlindemo.store

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import androidx.lifecycle.lifecycleScope
import kotlinx.android.synthetic.main.activity_test_flow.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import libcore.kotpref.AppSp.name
import org.jaaksi.kottlindemo.R

class TestStoreActivity : AppCompatActivity() {
    // At the top level of your kotlin file:
    val dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test_flow)

        btn.setOnClickListener {
            lifecycleScope.launch {
                get1()
            }
        }
    }

    private suspend fun get1() {
        val name = withContext(Dispatchers.IO) {
            dataStore.data.first()[stringPreferencesKey("name")]
        }
        println(name)
    }

    private suspend fun get2() {
        val flow = dataStore.data.map { it[stringPreferencesKey("name")] }
        flow.flowOn(Dispatchers.IO).collect {

        }


    }
}